package com.tct.worktimeboard.service.impl;

import com.alibaba.druid.sql.PagerUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tct.worktimeboard.config.DataSourceContextHolder;
import com.tct.worktimeboard.config.DataSourceEnum;
import com.tct.worktimeboard.entity.UserInfo;
import com.tct.worktimeboard.entity.WorkGroup;
import com.tct.worktimeboard.entity.WorkGroupVO;
import com.tct.worktimeboard.log.DataSource;
import com.tct.worktimeboard.mapper.GroupTypeMapper;
import com.tct.worktimeboard.mapper.UserInfoMapper;
import com.tct.worktimeboard.mapper.WorkGroupMapper;
import com.tct.worktimeboard.service.IWorkGroupService;
import com.tct.worktimeboard.util.JsonUtil;
import com.tct.worktimeboard.util.TimeUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Huhailong
 * @Description
 * @Date 2021/2/23.
 */
@Service
public class WorkGroupServiceImpl extends ServiceImpl<WorkGroupMapper, WorkGroup> implements IWorkGroupService {
    @Resource
    WorkGroupMapper workGroupMapper;
    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    GroupTypeMapper groupTypeMapper;

    /**
     * 创建群组
     * @param workGroupVO 群组类
     * @return 返回创建状态
     */
    @Transactional
    @Override
    public JSONObject createGroup(WorkGroupVO workGroupVO) {
        List<Long> userList = workGroupVO.getUserIdList();
        List<Long> powerUserIdList = workGroupVO.getPowerUserIdList();
        WorkGroup workGroup = workGroupVO.getWorkGroup();
        Integer count = workGroupMapper.selectCount(new QueryWrapper<WorkGroup>().eq("group_name", workGroup.getGroupName()));
        if(count>0){
            return JsonUtil.toErrorData("群组已存在，请勿重复创建");
        }
        workGroup.setCreateTime(TimeUtil.getDateTime());
        workGroupMapper.insert(workGroup);
        workGroupMapper.bindGroupUser(workGroup.getId(), userList);
        workGroupMapper.bindGroupPowerUser(workGroup.getId(),powerUserIdList);
        return JsonUtil.toJsonData();
    }

    @Override
    public JSONObject getGroupList(WorkGroup workGroup) {
        if(workGroup.isPaged()){
            PageHelper.startPage(workGroup.getPageNum(),workGroup.getPageSize());
        }
        QueryWrapper<WorkGroup> queryWrapper = new QueryWrapper<>();
        if(workGroup.getGroupName() != null && !workGroup.getGroupName().isEmpty()){
            queryWrapper.like("group_name",workGroup.getGroupName());
        }
        List<WorkGroup> workGroups = workGroupMapper.selectList(queryWrapper);
        workGroups.forEach(item-> item.setGroupTypeName(getGroupTypeNameById(item.getGroupTypeId())));
        return JsonUtil.toJsonData(new PageInfo<>(workGroups));
    }

    private String getGroupTypeNameById(Long id){
        return groupTypeMapper.selectById(id).getKindName();
    }

    @Transactional
    @Override
    public JSONObject deleteGroup(List<Long> ids) {
        workGroupMapper.deleteBatchIds(ids);
        workGroupMapper.deleteGroupUser(ids);
        workGroupMapper.deletePowerUser(ids);
        return JsonUtil.toJsonData();
    }

    @Override
    public JSONObject updateGroup(WorkGroupVO workGroupVO) {
        WorkGroup workGroup = workGroupVO.getWorkGroup();
        List<Long> userIdList = workGroupVO.getUserIdList();
        List<Long> powerUserIdList = workGroupVO.getPowerUserIdList();
        workGroupMapper.updateById(workGroup);
        List<Long> groupId = new ArrayList<>();
        groupId.add(workGroup.getId());
        workGroupMapper.deleteGroupUser(groupId);
        workGroupMapper.bindGroupUser(workGroup.getId(),userIdList);
        workGroupMapper.deletePowerUser(Collections.singletonList(workGroup.getId()));
        workGroupMapper.bindGroupPowerUser(workGroup.getId(),powerUserIdList);
        return JsonUtil.toJsonData();
    }

    /**
     * 根据群组获取该群组下的用户
     * @param groupId 群组ID
     * @return 返回用户列表
     */
    @Override
    public JSONObject getUserByGroup(Long groupId) {
        List<LinkedHashMap<String, Object>> userByGroup = workGroupMapper.getUserByGroup(groupId);
        List<Long> ids = new ArrayList<>();
        for(LinkedHashMap<String,Object> linkedHashMap:userByGroup){
            ids.add(Long.valueOf(String.valueOf(linkedHashMap.get("userId"))).longValue());
        }
        DataSourceContextHolder.clear();
        DataSourceContextHolder.setContextHolder("db2");
        if(ids.size()==0){
            DataSourceContextHolder.clear();
            return JsonUtil.toJsonData(new ArrayList<>());
        }
        List<UserInfo> userInfoById = getUserInfoById(ids);
        DataSourceContextHolder.clear();
        return JsonUtil.toJsonData(userInfoById);
    }

    public List<UserInfo> getUserInfoById(List<Long> ids){
        return userInfoMapper.selectBatchIds(ids);
    }

    /**
     * 根据群组获取该群组下的审批人
     * @param groupId 群组ID
     * @return 返回审批人列表
     */
    @Override
    public JSONObject getPowerUserByGroup(Long groupId) {
        List<LinkedHashMap<String, Object>> powerUserByGroup = workGroupMapper.getPowerUserByGroup(groupId);
        return JsonUtil.toJsonData(powerUserByGroup);
    }

    @Override
    public JSONObject getGroupIdListByUserId(Long userId) {
        List<Long> groupIdByUserId = workGroupMapper.getGroupIdByUserId(userId);
        return JsonUtil.toJsonData(groupIdByUserId);
    }

    @Override
    public JSONObject getGroupPowerUserId(Long userId) {
        List<Long> groupPowerUserIdByUserId = workGroupMapper.getGroupPowerUserIdByUserId(userId);
        List<Long> collect = groupPowerUserIdByUserId.stream().distinct().collect(Collectors.toList());
        return JsonUtil.toJsonData(collect);
    }

    /**
     * 根据用户ID获取所属群组
     * @param userId
     * @return
     */
    @Override
    public JSONObject getGroupByUserId(Long userId) {
        return JsonUtil.toJsonData(workGroupMapper.getGroupByUserId(userId));
    }
}
